<template>
  <div class="app-container">

    <!--查询列-->
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="项目" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="项目" clearable class="filter-item" @keyup.enter.native="handleFilter" />
      </el-form-item>
      <el-form-item label="渠道" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="渠道" clearable class="filter-item" @keyup.enter.native="handleFilter" />
      </el-form-item>
      <el-form-item label="内部状态">
        <el-select v-model="queryParams.purchStatus" placeholder="审核状态" clearable class="filter-item">
          <el-option v-for="item in this.purchStatusOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="报单时间">
        <el-date-picker
          v-model="promotionDate"
          class="filter-item"
          type="daterange"
          align="right"
          value-format="yyyy-MM-dd HH:mm:ss"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--操作列-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['purch:order:export']" type="warning" icon="el-icon-download" size="mini" :disabled="multiple" @click="handleExport">导出图片</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['purch:order:export']" type="success" icon="el-icon-download" size="mini" :loading="downloadLoading" @click="handleCart">加购数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['purch:order:export']" type="danger" icon="el-icon-download" size="mini" :loading="downloadLoading" @click="handleDownload">导出数据</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <!--数据表列-->
    <el-table ref="orderTable" :key="tableKey" v-loading="listLoading" :data="list" highlight-current-row style="width: 100%;" @sort-change="sortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" :index="indexMethod" />
      <el-table-column label="项目名称" width="120px">
        <template slot-scope="{row}">
          <span>{{ row.projectName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="渠道" width="60px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="代购折扣金额" width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.purchAmount }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="账号" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.account }}</span>
        </template>
      </el-table-column>
      <el-table-column label="密码" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.password }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电话" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.receiveName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地址" width="300px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.receiveAddress }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品截图" width="150px" align="center">
        <template slot-scope="{row}">
          <span>
            <div class="demo-image__preview">
              <el-image style="width: 50px; height: 50px" :src="row.skuImgs[0]" :preview-src-list="row.skuImgs" />
            </div>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="报单时间" width="160px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" width="80px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.orderStatus | statusUIMapFilter">{{ orderStatusFormat(row,row.orderStatus) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="代购状态" width="80px" align="center">
        <template slot-scope="{row}">
          <el-tag v-hasPermi="['purch:order:update']" :type="row.purchStatus | statusUIMapFilter">{{ purchStatusFormat(row,row.purchStatus) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button v-hasPermi="['purch:order:update']" type="text" size="mini" icon="el-icon-edit" @click="handleUpdate(row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页列-->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.limit" @pagination="getList" />
  </div>
</template>

<script>
import { Notification, Message } from 'element-ui'
import { tableInfo, crudUtil, sortUtil } from '@/utils/future/toolkit'
import { downLoadZip } from '@/utils/future/zipdownload'
import { fetchOrderList, fetchOrder, updateOrder, deleteOrder, refundOrder } from '@/api/purch/purchOrder'
import { fetchScheduleByIds } from '@/api/purch/purchSchedule'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const statusUIOptions = [
  { key: '-2', value: 'danger' },
  { key: '-1', value: 'danger' },
  { key: '0', value: 'success' },
  { key: '1', value: 'info' },
  { key: '2', value: 'primary' },
  { key: '3', value: 'primary' }
]

export default {
  name: 'PurchOrder',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusUIMapFilter(activityStatus) {
      const statusMap = statusUIOptions.reduce((acc, cur) => {
        acc[cur.key] = cur.value
        return acc
      }, {})
      return statusMap[activityStatus]
    }
  },
  data() {
    const tableData = {
      idKey: 'id',
      // 显示搜索条件
      showSearch: true,
      downloadLoading: false,
      // 搜索条件
      queryParams: {
        projectName: undefined,
        createUid: undefined,
        activityStatus: null
      },
      promotionDate: [],
      // 列表序号
      indexMethod: 1,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      orderStatusOptions: [],
      purchStatusOptions: [],
      approvalStatusOptions: [],
      options: [{ value: '0', label: '信息不完善' }, { value: '1', label: '未跟单' }, { value: '2', label: '其他' }],

      approvalOpen: false,
      confirmOpen: false,
      title: '',
      purchOrder: { timelineList: [] },
      form: { id: '', approvalStatus: '', approvelResult: '', remark: '' }
    }

    return Object.assign(tableData, tableInfo)
  },
  created() {
    this.getList()
    this.getDicts('purch_status').then(response => {
      this.purchStatusOptions = response
    })
    this.getDicts('bbs_order_status').then(response => {
      this.orderStatusOptions = response
    })
    this.getDicts('bbs_approval_status').then(response => {
      this.approvalStatusOptions = response
    })
  },
  methods: {
    toPurchSchedule(scheduleId) {
      Message({ message: '恭喜你，确认跟单成功', type: 'success' })
      var that = this
      this.$router.push({ name: 'ScheduleUpdate', query: { scheduleId: scheduleId }})
    },
    getList() {
      var that = this
      const queryParams = that.addDateRange(this.queryParams, this.promotionDate)
      that.queryParams = queryParams
      crudUtil.getList(that, fetchOrderList)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.promotionDate = []
      this.resetForm('queryForm')
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.refundData = selection
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    handleExpand(row, expandedRows) {

    },
    // 重置表单
    reset() {
      this.form = { id: '', approvalStatus: '', approvelResult: '', remark: '' }
    },
    // 更新页面
    handleUpdate(row) {
      var that = this
      this.$router.push({ name: 'PurchOrderUpdate', query: { orderId: row.id }})
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      queryParams.ids = this.ids
      this.$confirm('是否确认导出所有订单数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return downLoadZip('/purch/order/export', queryParams)
      })
    },
    // 订单状态字典翻译
    orderStatusFormat(row, status) {
      return this.selectDictLabel(this.orderStatusOptions, status)
    },
    // 代购状态字典翻译
    purchStatusFormat(row, status) {
      return this.selectDictLabel(this.purchStatusOptions, status)
    },
    // 审批状态字典翻译
    approvelStatusFormat(status) {
      const ss = this.selectDictLabel(this.approvalStatusOptions, status)
      console.log(ss, status)
      return ss
    },

    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        sortUtil.sortByID(order)
      }
    },
    // 导出加购数据
    handleCart() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['编号', '账号', '密码', '代码', '归属', '端口', '来源', '价格', '电话', '姓名', '地址']
        const filterVal = ['id', 'account', 'password', 'linkUrl', 'ascription', 'interfaced', 'linkName', 'cartPrice',
          'phone', 'receiveName', 'receiveAddress']
        const list = this.list
        const ids = list.map(order => order.purchScheduleId)
        fetchScheduleByIds({ ids: ids }).then(res => {
          list.map(order => {
            if (res[order.purchScheduleId]) {
              const purchSchedule = res[order.purchScheduleId]
              order.linkUrl = purchSchedule.linkUrl
              order.ascription = purchSchedule.ascription
              order.interfaced = purchSchedule.interfaced
              order.linkName = purchSchedule.linkName
              return order
            }
          })
        })
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({ header: tHeader, data, filename: '加购数据' })
        this.downloadLoading = false
      })
    },
    // 导出代购订单数据
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['编号', '项目名称', '渠道', '商品金额', '账号', '密码', '电话', '姓名', '地址', '备注', '商品截图', '报单时间', '订单状态', '代购状态']
        const filterVal = ['id', 'projectName', 'userName', 'skuPrice', 'account', 'password', 'phone', 'receiveName', 'receiveAddress', 'remark', 'skuImg', 'createTime', 'orderStatus', 'purchStatus']
        const list = this.list
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({ header: tHeader, data, filename: '代购数据' })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else if (j === 'orderStatus') {
          return this.orderStatusFormat(null, v[j])
        } else if (j === 'purchStatus') {
          return this.purchStatusFormat(null, v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 20%;
  }

</style>
